package tms.business.mail;

import tms.model.login.UserEntity;
import tms.util.context.WebContext;
import tms.util.exception.ApplicationRuntimeException;

import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import java.util.List;


@MessageDriven(mappedName = "TmsNotificationsQueue")
public class MailSenderMdb implements MessageListener {
    @EJB
    MailService mailService;

    @Override
    @SuppressWarnings("unchecked")
    public void onMessage(Message message) {
        if (WebContext.getMailConfig() != null && message instanceof ObjectMessage) {
            ObjectMessage objectMessage = (ObjectMessage)message;
            try {
                try {
                    List<UserEntity> users = (List<UserEntity>)objectMessage.getObject();
                    mailService.notifyUsers(users);
                } catch (JMSException e) {
                    throw new ApplicationRuntimeException(e);
                }
            } catch (ApplicationRuntimeException e) {
                e.printStackTrace();
            }
        }
    }
}
